package com.shihan.service;

import com.shihan.lock.RedisLock;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description 用于简单测试 分布式锁的业务类
 * @Author shihan
 * @Date 2021/1/26 19:14
 **/
public class OrderService {

    public static final String LOCK_KEY = "redis_lock_key";

    /**
     * 竞争等待的超时时间，单位：毫秒
     */
    public static final int WAIT_TIMEOUT = 5000;

    /**
     * key 的生命周期时长，单位：毫秒
     */
    public static final int KEY_TIME_OUT = 10000;

    public static void bizService() {
        // 1、获取锁
        RedisLock redisLock = new RedisLock();
        String lockValue = redisLock.getLock(LOCK_KEY, WAIT_TIMEOUT, KEY_TIME_OUT);

        // 2、成功获取到锁后，正常执行业务逻辑
        if (StringUtils.isEmpty(lockValue)) {
            System.out.println(Thread.currentThread().getName() + " 获取锁失败！");
            return;
        }

        System.out.println(Thread.currentThread().getName() + " 获取锁成功！");
        System.out.println(Thread.currentThread().getName() + " lockValue：" + lockValue);

        // 3、释放锁
        boolean unlock = redisLock.unlock(LOCK_KEY, lockValue);

        if (!unlock) {
            throw new RuntimeException(Thread.currentThread().getName() + "锁释放失败！");
        }
    }

    /**
     * 简单的测试
     *
     * @param args
     */
    public static void main(String[] args) {
        bizService();
    }

}
